package com.yifeng.nettyclient;

import com.yifeng.netty.common.protobuf.UserInfo;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.concurrent.TimeUnit;

public class NettyClient {
    private final String HOST = "127.0.0.1";
    private final int PORT = 8090;
    private ChannelFuture future;

    public NettyClient(){
        init();
    }

    public void init() {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline p = ch.pipeline();
                            p.addLast(new IdleStateHandler(5, 0, 0, TimeUnit.SECONDS));
                            // 解码和编码，应和客户端一致
                            //传输的协议 Protobuf
                            p.addLast(new ProtobufVarint32FrameDecoder());
                            p.addLast(new ProtobufDecoder(UserInfo.UserMsg.getDefaultInstance()));
                            p.addLast(new ProtobufVarint32LengthFieldPrepender());
                            p.addLast(new ProtobufEncoder());
                            p.addLast(new ClientHandler());
                        }
                    });
            future = b.connect(HOST, PORT).sync();
//            for(int i = 0;i<100;i++){
//                UserInfo.UserMsg userMsg = UserInfo.UserMsg.newBuilder().setId(i).setAge(18).setName("xuwujing").setState(1)
//                        .build();
//                future.channel().writeAndFlush(userMsg);
//            }

            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            group.shutdownGracefully();
        }
    }
    public void sendMessage(String content){
        future.channel().writeAndFlush(content);
    }

}